<template>
  <div class="resetPassword">
    <div class="reset-content" v-if="isShowReset">
      <div class="reset-title">重置密码</div>
      <div class="reset-tips">
        <span v-if="isShowIphone">
          输入与你账户绑定的手机号，以便获取验证码
        </span>
        <span v-else>
          一条验证码已发送到手机后四位{{lastPhone}}的手机，请输入验证码继续。
        </span>
      </div>
      <div class="number">
        <div class="login-input-row" v-if="isShowIphone">
          <div class="login-label">手机号</div>
          <div class="login-input">
            <input
              class="login-inp"
              name="phone"
              ref="phoneInp"
              v-validate="'required|phone'"
              v-model="resetphoneNumbs" 
              :maxlength="11"
              type="text"
              autofocus="autofocus"
              @keyup.enter="continuePhone"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('phone')" class="el-form-item__error">
            {{ errors.first("phone") }}
          </div>
        </div>
        <div v-if="isShowCode" class="login-input-row">
          <div class="login-label">验证码</div>
          <div class="login-input">
            <input
              class="login-inp"
              v-model="codeNumbs" 
              ref="smsInp"
              type="text"
              autofocus="autofocus"
              :maxlength="6"
              @keyup.enter="continuePassword"
              @keydown="keyDown($event)"
            />
          </div>
        </div>

      </div>

      <div
        v-if="isShowSendCode"
        class="again-code"
      >
        <div 
          :disabled="disabled"
          class="blueColor"
          :class="{'grayColor': disabled}"
          @click="againSendCode"
        >
          重新发送验证码
          <span v-show="isShowCount">({{ count }})s</span>
        </div>
      </div>
      
      <div class="step-btns" v-if="!isShowPassword">
        <div class="step-btn" @click="goBackPhone">返回</div>
        <div @click="continuePassword" class="step-btn active">继续</div>
      </div>
      <div class="step-btns" v-else>
        <div class="step-btn" @click="goBackLogin">返回</div>
        <div @click="continuePhone" class="step-btn active">继续</div>
      </div>
      <other-way />
      
    </div>

    <!-- 新密码 -->
    <div class="reset-content" v-if="isShowNewPassword">
      <div class="reset-title">新密码</div>
      <div class="reset-tips">
        <span>新的账户密码</span>
      </div>
      <div class="reset-passwords">
        <div class="reset-input-row">
          <div class="reset-label">新密码</div>
          <div class="reset-input">
            <input
              class="reset-inp"
              name="newpassword"
              ref="pwdInp"
              v-validate="'required|newpassword'"
              v-model="resetForm.password"
              type="password"
              placeholder="请输入新密码"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('newpassword')" class="el-form-item__error">
            {{ errors.first("newpassword") }}
          </div>
        </div>
        <div class="reset-input-row">
          <div class="reset-label">确认密码</div>
          <div class="reset-input">
            <input
              class="reset-inp"
              autocomplete="off"
              v-model="resetForm.repassword"
              placeholder="请再次输入新密码"
              v-validate="'required|confirmed:newpassword|new-password'"
              data-vv-as="newpassword"
              name='renew_password'
              type="password"
              @keyup.enter="toLogin"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('renew_password')" class="el-form-item__error">
            {{ errors.first('renew_password') }}
          </div>

          
        </div>
      </div>
      <div class="step-btns">
        <div class="step-btn" @click="goBackNewCount">返回</div>
        <div @click="toLogin" class="step-btn active">继续</div>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from "@/api";
export default {
  data() {
    return {
      isShowIphone: true,
      action: "ipHone",
      isShowPassword: true,
      isShowReset: true,
      isShowCount: true,
      disabled: true,
      isShowCode: false,
      isShowSendCode: false, // 倒计时
      timer: "",
      count: 60,
      isShowNewPassword: false,
      resetphoneNumbs: '',
      codeNumbs: '',
      resetForm: {
        password: "",
        repassword: "",
      },
      lastPhone: "",
      user_id: "",
      type: "",
    };
  },
  watch: {
    isShowIphone() {
      setTimeout(() => {
        this.$refs.phoneInp.focus()
      }, 800)
    },
    isShowCode() {
      setTimeout(() => {
        this.$refs.smsInp.focus()
      }, 800)
    },
    isShowNewPassword() {
      setTimeout(() => {
        this.$refs.pwdInp.focus()
      }, 800)
    }
  },
  methods: {
    keyDown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false
      }
    },
    // 重置密码的继续
    continuePhone() {
      let phone = this.resetphoneNumbs
      if (phone && phone.length == 11 && /^1[3-9]\d{9}$/.test(phone)) {
        this.lastPhone = phone.substr(phone.length - 4);
        this.phoneCheck(1, phone)
        
      } else if (phone.length === 0) {
        this.$message.warning("手机号不能为空");
        return false;
      } else {
        this.$message.warning("请输入正确的手机号");
        return false;
      }
    },

    // 获取倒计时
    getCode() {
      console.log('reset开始倒计时了： ')
      const Total_time = 60;
      if (!this.timer) {
        this.count = Total_time;
        this.isShowSendCode = true;
        this.isShowCount = true;
        this.disabled = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= Total_time) {
            this.count--;
          } else {
            // this.isShowSendCode = true;
            this.disabled = false;
            this.isShowCount = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    // 新密码
    continuePassword() {

      if (!this.codeNumbs || this.codeNumbs.length !== 6 || isNaN(this.codeNumbs)) {
        this.$message.warning("验证码必须是6位数字");
        return false;
      }

      // 验证码与返回的验证码进行判断
      this.loginVerifyCode();
    },


    // 返回登录
    goBackLogin() {
      this.$emit("goBackLogin", this.isShowReset);
    },

    // 返回手机号
    goBackPhone() {
      this.$nextTick(() => {
        this.codeNumbs = '';
      });
      this.isShowCode = false;
      this.isShowPassword = true;
      this.isShowSendCode = false;
      this.isShowIphone = true;
    },
    //返回验证码
    goBackNewCount() {
      this.doClear()

      this.isShowNewPassword = false;
      this.isShowReset = true;
      this.isShowIphone = true;
      this.isShowCode = false;
      this.isShowSendCode = false;
      this.isShowPassword = true;
    },

    // 再次点击发送验证码
    againSendCode() {
      if (this.disabled) {
        return false;
      }
      this.smsVerifyCode();
    },

    doClear() {
      clearInterval(this.timer)
      this.timer = null
      this.count = 60
    },

    // 跳回登录页
    toLogin() {
      console.log('重置： 继续: ', this.$validator)
      this.$validator.validateAll().then((valid) => {
        console.log('重置： 继续: ', valid)
        if (valid) {
          this.loginResetPassword();
        }
      });
    },
    
    
    // 检查手机号是否存在
    async phoneCheck(type, phone) {
      let params = {
        phone,
        type
      }
      const { code, data, message } = await api.login(this).phoneCheck(params);
      if (code === 0) {
        this.smsVerifyCode()
      }
    },

    //重置密码
    async loginResetPassword() {
      let resetUser = {};
      resetUser.user_id = this.user_id;
      resetUser.password = window.btoa(this.resetForm.password);
      //0-系统用户 1-客户
      if (this.type == null) {
        resetUser.type = 0;
      } else {
        resetUser.type = 1;
      }
      const { code, data, message } = await api
        .login(this)
        .loginResetPassword(resetUser);
      if (code === 0) {
        this.isShowNewPassword = false;
        this.$message.success("密码修改成功！");
        this.$emit("toLogin", this.resetForm);
      }
    },

    // 发送短信验证码
    async smsVerifyCode() {
      let pramas = {};
      pramas.phone = this.resetphoneNumbs
      const { code, data, message } = await api
        .login(this)
        .smsVerifyCode(pramas);
      if (code === 0) {
        this.$message.success("获取短信验证码！");
        this.isShowIphone = false;
        this.isShowCode = true;
        this.isShowPassword = false;
        this.isShowSendCode = true;
        this.$nextTick(() => {
          this.codeNumbs = '';
        });
        this.getCode();
      }
    },
    //短信验证码登录
    async loginVerifyCode() {
      let pramas = {};
      pramas.phone = this.resetphoneNumbs
      pramas.code = this.codeNumbs
      const { code, data, message } = await api
        .login(this)
        .loginVerifyCode(pramas);
      if (code === 0) {
        localStorage.setItem("access_token", data.access_token);
        this.isShowReset = false;
        this.isShowNewPassword = true;
        this.user_id = data.user_id;
        //0-系统用户 1-客户
        this.type = data.organization_id;
        this.$validator.reset()
      }
    },
  },
  //

  created() {},
  mounted () {
    setTimeout(() => {
      this.$refs.phoneInp.focus()
    }, 800)
  },
  destroyed() {
    clearInterval(this.timer);
  },
};
</script>

<style>
</style>